/**
 * 
 */
package com.colombounplug.geoshopper;

import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import javax.net.ssl.HttpsURLConnection;

/**
 * @author anuradha.uduwage
 *
 */
public class CompareItemTab extends ListActivity {
	
	URL apiUrl;
	//private GlobalState state;
	//ShoppingListDbAdapter  shopList;
	//Context context;
	ArrayList<String> items = new ArrayList<String>();
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void onCreate(Bundle savedInstanceState) {
	  super.onCreate(savedInstanceState);
	  //ArrayList<String> list = new ArrayList<String>();
	  //state = (GlobalState) getApplication();
	// Get values
	  GlobalState gs = (GlobalState) getApplication();
	  items = gs.getItems();
	  Log.v("item:", items.get(0));
	  setListAdapter(new ArrayAdapter(this, R.layout.comparelist, items));
	  //setListAdapter(new ArrayAdapter(this, R.layout.comparelist, list));

	  ListView lv = getListView();
	  lv.setTextFilterEnabled(true);

	  lv.setOnItemClickListener(new OnItemClickListener() {
	    public void onItemClick(AdapterView<?> parent, View view,
	        int position, long id) {
	    	ArrayList<String> listItems = new ArrayList<String>();
	    	//String itemPrice;
	      // When clicked, show a toast with the TextView text
	      /*Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
	          Toast.LENGTH_SHORT).show();*/
	    	try {
	    		try {
	    			String response = googleShoppingRequest((String) ((TextView) view).getText());
	    			JSONObject jo = new JSONObject(response);
	    			JSONArray ja = new JSONArray();
	    			ja = (JSONArray) jo.get("items");
	    			for (int i = 0; i < ja.length(); i++) {
	    				JSONObject jobj = (JSONObject) ja.get(i);
	    				JSONObject product = (JSONObject) jobj.get("product");
	    				JSONArray inventories = new JSONArray();
	    				inventories = (JSONArray) product.get("inventories");
	    				JSONObject price = (JSONObject) inventories.get(0);
	    				JSONObject author = (JSONObject) product.get("author");
	    				//itemPrice = price.getString("price");
	    				listItems.add("Title: " + product.getString("title") + "\nStore: " + author.getString("name") + "\nPrice: " + price.getString("price"));
	    				Log.v("blah",price.getString("price"));
	    			}
	    		} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (JSONException e) {
					e.printStackTrace();
				}
	    	} catch (MalformedURLException e) {
	    		e.printStackTrace();
	    	} catch (IOException e) {
	    		e.printStackTrace();
	    	}
			setListAdapter(new ArrayAdapter(CompareItemTab.this, R.layout.comparelist, listItems));
	    		/*AlertDialog alertDialog = new AlertDialog.Builder(CompareItemTab.this).create();
	    		alertDialog.setTitle("Cheapest online price");
	    		alertDialog.setMessage("Random");
	    		alertDialog.show();*/
	    }
	  });
	}
	static final String[] COUNTRIES = new String[] {
	    "iPod", "iPhone", "Macbook Pro", "Magic Mouse", "Wireless Keyboard"};
	
	public String googleShoppingRequest(String q) throws MalformedURLException, IOException {
		String url = "https://www.googleapis.com/shopping/search/v1/public/products?key=AIzaSyCb5f2eRu3yFXAgALMzIbra5y5dlDN-dfk&country=US&alt=json&maxResults=10&q="+q;
		StringBuilder response = new StringBuilder();
		Log.v("google shopping", "url : " + url);
		apiUrl = new URL(url);
		
		HttpURLConnection httpConn = (HttpURLConnection) apiUrl.openConnection();
		if(httpConn.getResponseCode() == HttpsURLConnection.HTTP_OK) {
			BufferedReader input = new BufferedReader(new InputStreamReader(httpConn.getInputStream()), 8192);
			String strLine = null;
			while((strLine = input.readLine()) != null) {
				response.append(strLine);
			}
			input.close();
		}
		return response.toString();
	}
	
	@Override
	public void onBackPressed() {
		setListAdapter(new ArrayAdapter<String>(this, R.layout.comparelist, items));
		return;
	}

}
